var curTryNum = 0;
var maxTryNum = 5;
var stompClient = null;
var socket = null;
var isOpenedChatBox = false;//标记聊天窗口是否打开
var receiveMsg = {};
var tempMsg = {};
var curSendTargetUser;
var curSendTargetId = {};
var containChatItems = {};
var chatIndex;
layui.use(['element', 'form', 'layer', 'laytpl'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        element = layui.element,
        form = layui.form,
        laytpl = layui.laytpl;

    // var count;     //每次获取的商品数
    // var limit = 10;     //每页显示条目数
    // var curPageGoods = {};
    // var goods = {};
    var categories = {};
    var curGoodsId;
    var headImgPrefix = '../upload/img/header/';
    // var hash = "index.html#!goods/";

    $(document).ready(function () {
        addEventListener();
        initRoute();
        // getGoodsByCategory("最新发布");
        initGoToTop();
        $(window).resize(function () {
            initGoToTop();
        });
        $(window).scroll(function () {
            initGoToTop();
        });

        initSockJs();
        getHistory();

    });

    $(document).ready(function () {
        $("#nicknameId").text(localStorage.getItem("nickname"));
        $("#userHeadImg").attr('src', headImgPrefix + localStorage.getItem("headerImg"));
        $.ajax({
            url: "category.json",
            async: true,
            dataType: "json",
            success: function (data) {
                categories = data;
                addEventListener();
            }
        });

    });

    function addEventListener() {
        $("#logoutBtn").click(function () {
            logout();
        });

        // $(document).on('click', '#userHeader', function () {
        //     location.href = 'home.html';
        // });

        $("#toTop").click(function () {
            $(window).scrollTop(0);
            return false;
        });


        //聊天框左侧列表监听

        $(document).on('mouseover', 'div#chatItem', function () {
            $(this).css("background-color", "#d2d2d2");
        });
        $(document).on('mouseout', 'div#chatItem', function () {
            $(this).css("background-color", "#FFFFFF");
        });

        $(document).on('click', 'div#chatItem', function () {
            //保存之前信息

            tempMsg[curSendTargetUser] = $('#content').html();
            console.log(tempMsg[curSendTargetUser]);
            $('#content').html("");

            curSendTargetUser = $(this).text().trim();

            layer.title('正在与'+curSendTargetUser+'聊天', chatIndex);
            $(this).css("color", "#0000FE");
            console.log(curSendTargetUser);

            //渲染
            renderChatBox();

        });

    }

    //我要发布
    $('#publishing').on('click', function () {
        layer.open({
            title: '我要发布',
            type: 1,
            content: $('#publishing_form').html(),
            area: '400px',
            success: function (layero, index) {
                renderSelectCategory();
                form.render('select');
                form.on('submit(publish-filter)', function () {
                    // $("#submitBtn").prop("disabled", true);
                    var goodsForm = document.getElementById("publishForm");
                    var data = new FormData(goodsForm);
                    data.append("userId", localStorage.getItem("userId"));
                    data.append("timeCreate", new Date().Format("yyyy-MM-dd HH:mm:ss"));
                    $.ajax({
                        type: "POST",
                        url: '/api/publish.do?',
                        enctype: 'multipart/form-data',
                        data: data,
                        processData: false,
                        contentType: false,
                        cache: false,
                        timeout: 6000,
                        success: function (ret) {
                            // $("#btnSubmit").prop("disabled", false);
                            if (ret.code === 0) {
                                layer.msg("发布成功");
                            }
                            if (ret.code === 2 || ret.code === 3) {
                                layer.msg(ret.msg);
                                logout();
                            }
                            setTimeout(function () {
                                layer.closeAll();
                            }, 1000);
                        },
                        error: function (e) {
                            // $("#btnSubmit").prop("disabled", false);
                        }
                    });
                    return false;
                })
            }
        });
    });

    //我的发布
    $('#published').on('click', function () {
        $.getJSON('goodsImg.json', function (json) {
            layer.photos({
                photos: json
                , tab: function (pic, layero) {
                    console.log(pic) //当前图片的一些信息
                }
                , anim: 3 //0-6的选择，指定弹出图片动画类型，默认随机
            });
        });
    });

    //分页选择页数 监听
    // $('.sel').on("change", function () {
    //     paging(goods, 1);
    //     renderGoods(curPageGoods);
    // });
    //
    // //处理页数与商品映射
    // function paging(goods, pageNum) {
    //     pageNum = parseInt(pageNum);
    //     var singletonPageGoods = [];
    //     var start = (pageNum - 1) * limit;
    //     var end = (start + limit) > count ? count : start + limit;
    //     for (var i = start; i < end; i++) {
    //         singletonPageGoods[i - start] = JSON.stringify(goods.list[i]);
    //     }
    //     curPageGoods.list = JSON.parse('[' + singletonPageGoods.toString() + ']');
    // }
    //
    // //异步渲染数据
    // function renderGoods(data) {
    //     var getTpl = goodBoxTpl.innerHTML
    //         , view = document.getElementById('goods-list');
    //     laytpl(getTpl).render(data, function (html) {
    //         view.innerHTML = html;
    //     });
    // }
    //
    // //分页
    // function renderPages(count) {
    //     $('#all_number_sz').text(count);
    //     laypage.render({
    //         elem: 'sz_page_box',
    //         limit: limit,
    //         layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
    //         groups: 4,
    //         count: count, //从服务端取得,
    //         jump: function (obj, first) {
    //             limit = obj.limit;
    //             paging(goods, 1);
    //             if (!first) {
    //                 paging(goods, obj.curr);
    //             }
    //             renderGoods(curPageGoods);
    //         }
    //     });
    // }
    //
    // //渲染左侧side
    // function renderLeftSide() {
    //     var getTpl = leftSideTpl.innerHTML,
    //         view = document.getElementById('left-side');
    //     laytpl(getTpl).render(categories, function (html) {
    //         view.innerHTML = html;
    //     });
    // }
    //
    //
    // //单张图片上传
    // // function uploadImg() {
    // //
    // //     var uploadInst = upload.render({
    // //         elem: '#uploadBtn'
    // //         , url: '/api/publish.do'
    // //         , auto: false
    // //         , bindAction: '#submitBtn'
    // //         , choose: function (obj) {
    // //             obj.preview(function (index, file, result) {
    // //                 $('#goodsImg').val(file.name);
    // //             });
    // //         }
    // //         , done: function (res, index, upload) {
    // //             //如果上传失败
    // //             if (res.code > 0) {
    // //                 return layer.msg('上传失败');
    // //             }
    // //             //上传成功
    // //         }
    // //         , error: function () {
    // //             //失败状态，并实现重传
    // //             var errText = $('#errText');
    // //             errText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
    // //             errText.find('.demo-reload').on('click', function () {
    // //                 uploadInst.upload();
    // //             });
    // //         }
    // //     });
    // // }
    //
    // //添加图片路径前缀
    // function addImgPrefix(prefix) {
    //     console.log(goods.list);
    //     console.log(prefix)
    //     for (var length = goods.list.length, i = 0; i < length; i++) {
    //         goods.list[i].src = prefix.toString() + goods.list[i].src;
    //         //去掉分号;
    //         goods.list[i].src = goods.list[i].src.substr(0, goods.list[i].src.length - 1);
    //
    //         goods.list[i].pk_id = hash.toString() + goods.list[i].pk_id;
    //
    //         // console.log(goods.list[i].src);
    //         // console.log(goods.list[i].pk_id);
    //     }
    // }
    //
    //
    //
    //
    // //根据种类获取商品
    // function getGoodsByCategory(goodType) {
    //     var data = {};
    //     data.userId = localStorage.getItem("userId");
    //     $.ajax({
    //         url: "/api/goods/category/" + goodType,
    //         async: true,
    //         dataType: "json",
    //         timeout: 6000,
    //         success: function (ret) {
    //             if (ret.code === 0) {
    //                 layer.msg(ret.msg);
    //                 goods.list = ret.data;
    //                 goods.count = ret.data.length;
    //                 addImgPrefix(localStorage.getItem("prefix"));
    //                 console.log(goods);
    //                 count = goods.count;
    //                 $("h2").text(goodType);//更新小标题
    //                 renderPages(goods.count);//分页
    //                 $('#sz_page_box').css("margin", "0 auto");
    //                 layer.msg("加载成功");
    //             }
    //
    //             if (ret.code === '-1') {
    //                 layer.msg(ret.msg());
    //             }
    //
    //             if (ret.code === '2' || ret.code === '3') {
    //                 logout();
    //             }
    //             layer.closeAll();
    //         },
    //         error: function () {
    //             layer.closeAll('loading');
    //             layer.msg("加载失败");
    //         }
    //     });
    // }


    //我要发布表单中下拉框渲染
    function renderSelectCategory() {
        var getTpl = selectCategoryTpl.innerHTML,
            view = document.getElementById('selCategory');
        laytpl(getTpl).render(categories, function (html) {
            view.innerHTML = html;
        });
    }


    function initGoToTop() {
        if ($(window).scrollTop() === 0) {
            $(".go-to-top").hide();
        } else {
            $(".go-to-top").show();
        }
    }

    function initRoute() {
        Q.reg('newest', function () {
            loadView('newest');
        }).reg('home',function () {
            loadView('home');
        }).reg('goods', function (id) {
            console.log("goods id is " + id);
            sessionStorage.setItem("curGoodsId", id);
            console.log(Q.lash);
            loadView('goods');
        });

        Q.init({
            index: 'newest'
        });
    }

    function loadView(path) {
        $("#main").load("index/" + path + ".html", function () {
            console.log("change path to " + path);
        });
    }

    function initSockJs() {
        // var curTryNum = 0;
        // var maxTryNum = 5;
        // var stompClient = null;
        // var socket = null;
        var stompHeader = {'clientId': localStorage.getItem("userId")};

        Date.prototype.Format = function (format) {
            var o = {
                "M+": this.getMonth() + 1,
                "d+": this.getDate(),
                "H+": this.getHours(),
                "m+": this.getMinutes(),
                "s+": this.getSeconds(),
                "S+": this.getMilliseconds()
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return format;
        };

        connect("/api/chat/");


        function connect(url) {
            if (socket == null) {
                socket = new SockJS(url);
                stompClient = Stomp.over(socket);
                stompClient.heartbeat.outgoing = 20000;
                stompClient.heartbeat.incoming = 0;

            }
            curTryNum++;
            stompClient.connect(stompHeader, function (frame) {
                setConnected(true);
                console.log("连接成功：" + new Date().Format("yyyy-MM-dd HH:mm:ss") + +frame);


                //==================================user==================================
                stompClient.subscribe('/user/' + localStorage.getItem("userId") + '/message', function (reply) {
                    console.log(reply);
                    var fromName = JSON.parse(reply.body).fromName;

                    if (!containChatItems.hasOwnProperty(fromName)) {
                        containChatItems[fromName] = false;
                    }
                    console.log(fromName);

                    //当聊天窗口打开的情况下 收到消息
                    if (isOpenedChatBox && curSendTargetUser === fromName) {

                        //渲染右侧具体内容
                        var content = $('#content');
                        var c = getRenderReceiveMsg(JSON.parse(reply.body).headerImg, JSON.parse(reply.body).content);
                        console.log(c);
                        content.append(c);
                        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                    }
                    else {
                        //save message into receiveMsg;
                        if (!receiveMsg.hasOwnProperty(fromName)) {
                            receiveMsg[fromName] = [];
                            //队列Map
                            receiveMsg[fromName].unshift(reply);
                            curSendTargetId[fromName] = JSON.parse(reply.body).fromId;
                            console.log(receiveMsg[fromName]);
                        } else {
                            receiveMsg[fromName].unshift(reply);
                            console.log(receiveMsg[fromName]);

                        }
                        //聊天框左边显示通知
                        if (isOpenedChatBox) {
                            $('#chatList').append(renderChatList());
                            $('div.' + fromName).css("color", "#FF0000");
                        } else {
                            layer.open({
                                type: 1
                                , title: '您有新短消息'
                                , offset: 'rb'
                                , btn: '查看'
                                , btnAlign: 'r' //按钮居中
                                , shade: 0 //不显示遮罩
                                , yes: function () {
                                    layer.closeAll();
                                    openChatBox(reply);
                                }
                            });
                        }
                    }
                });
                //==================================topic=================================
                stompClient.subscribe('/topic/greeting', function (reply) {
                    console.log(reply);
                    var fromName = JSON.parse(reply.body).fromName;
                    if (receiveMsg[fromName] === null) {
                        receiveMsg[fromName] = [];
                        receiveMsg[fromName].push(reply);
                    } else {
                        receiveMsg[fromName].push(reply);
                    }
                    if (isOpenedChatBox) {
                        var content = $('#content');
                        var c = getRenderReceiveMsg(JSON.parse(reply.body).headerImg, JSON.parse(reply.body).content);
                        console.log(content);
                        console.log(c);
                        content.append(c);
                        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                    } else {
                        layer.open({
                            type: 1
                            , offset: 'rb'
                            , title: '您有新短消息'
                            , btn: '关闭全部'
                            , btnAlign: 'r' //按钮居中
                            , shade: 0 //不显示遮罩
                            , yes: function () {
                                layer.closeAll();
                                openChatBox();
                            }
                        });
                    }
                });


                //检测离线信息
                checkOfflineMsg();
            });


            //接收消息之后打开
            function openChatBox() {
                chatIndex = layer.open({
                    type: 1
                    , title: "正在与" + curSendTargetUser + "聊天"
                    , content: $('#chatLayer').html()
                    , area: 'auto'
                    , scrollbar: false
                    , maxWidth: 900
                    , maxHeight: 500
                    , success: function () {
                        console.log("打开聊天窗口aaaa");
                        isOpenedChatBox = true;
                        $('#chatList').append(renderChatList());

                        curSendTargetUser = $('div#chatItem').text().trim();
                        layer.title('正在与'+curSendTargetUser+'聊天', chatIndex);
                        $(this).css("color", "#0000FE");
                        console.log(curSendTargetUser);

                        //渲染
                        renderChatBox();

                        // var fromId = JSON.parse(reply.body).fromId;
                        // var toId = JSON.parse(reply.body).toId;
                        // var userList = renderChatList();
                        // $('#chatItem').append(userList);
                        // // $(document).on('keydown',function(event){
                        // //     if(event.keyCode === 13 && isOpenedChatBox===true){
                        // //         var edit = $('#editText');
                        // //         if (edit.val() === "") {
                        // //             layer.msg("输入的内容不能为空");
                        // //             return ;
                        // //         }
                        // //         var v = $('#content');
                        // //
                        // //         var c = getRenderSendMsg('../upload/img/header/header.png',edit.val());
                        // //
                        // //         var d = getRenderReceiveMsg('../upload/img/header/header.png',edit.val());
                        // //         v.append(c);
                        // //         v.append(d);
                        // //         stompClient.send("/ws/message", {},
                        // //             JSON.stringify({'fromId':21,'toId':22,'content':c}));
                        // //         edit.val("");
                        // //         document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                        // //     }
                        // // });
                        // if (reply != null) {
                        //     var content = $('#content');
                        //     var c = getRenderReceiveMsg(JSON.parse(reply.body).headerImg, JSON.parse(reply.body).content);
                        //     console.log(content);
                        //     console.log(c);
                        //     content.append(c);
                        //     document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                        // }

                        $(document).on("click",'#send', function () {
                            var edit = $('#editText');
                            if (edit.val() === "") {
                                return ;
                            }
                            var v = $('#content');

                            var headerImg = $("#userHeadImg").attr('src');
                            var c = getRenderSendMsg(headerImg,edit.val());

                            v.append(c);
                            stompClient.send("/ws/message", {},
                                JSON.stringify({'fromId':localStorage.getItem("userId"),'toId':curSendTargetId[curSendTargetUser],
                                    'fromName':localStorage.getItem('nickname'),'content':edit.val(),'headerImg':headerImg}));
                            edit.val("");
                            document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                        });
                    }
                    ,cancel:function () {
                        isOpenedChatBox = false;
                        tempMsg[curSendTargetUser] = $('#content').html();
                        clearMap(containChatItems);
                        console.log("关闭聊天窗口");
                    }
                });
            }
        }


        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("连接关闭 " + new Date().Format("yyyy-MM-dd HH:mm:ss"));
        }

        function setConnected(connected) {
            if (connected) {
                console.log("显示对话");
            } else {
                console.log("隐藏对话");
            }
        }
    }

    //获取聊天记录
    function getHistory() {
        $.ajax({
            url: "/api/message/history/"+localStorage.getItem("userId"),
            async: true,
            dataType: "json",
            success: function (ret) {
                if (ret.code === 0){
                    if(ret.count === 0){
                        console.log("没有聊天记录");
                    }else if (ret.count > 0){
                        console.log("聊天记录如下");
                        console.log(ret.data);
                        //显示聊天记录
                        showHistory(ret.data);
                    }else{
                        console.log(ret.count);
                    }
                }
                else if (ret.code === 9){
                    logout();
                }
            }
        })
    }

    //检测离线信息
    function checkOfflineMsg() {
        $.ajax({
            url: "/api/message/checkOffline/"+localStorage.getItem("userId"),
            async: true,
            dataType: "json",
            success: function (ret) {
                if (ret.code === 0){
                    if(ret.count === 0){
                        console.log("没有收到离线信息");
                    }else if (ret.count > 0){
                        console.log("接收到的离线信息为");
                        console.log(ret.data);
                    }else{
                        console.log(ret.count);
                    }
                }
                else{
                    console.log(ret);
                }
            }
        })
    }

    //显示聊天记录
    function showHistory(history) {

    }

    function renderChatBox() {

        var c = tempMsg.hasOwnProperty(curSendTargetUser)?tempMsg[curSendTargetUser]:"";
        var reply;
        var l = receiveMsg.hasOwnProperty(curSendTargetUser)?receiveMsg[curSendTargetUser].length:0;
        for (var i = 0; i < l; i++) {
            reply = receiveMsg[curSendTargetUser].pop();
            c = c + getRenderReceiveMsg(JSON.parse(reply.body).headerImg, JSON.parse(reply.body).content);
        }
        console.log(c);
        $('#content').append(c);
        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
    }
});


//=============================================全局函数=======================================================
function logout() {
    console.log("退出.........");
    localStorage.removeItem("prefix");
    localStorage.removeItem("userId");
    localStorage.removeItem("nickname");
    localStorage.removeItem("headerImg");
    location.href = '/html/login.html'
}

//渲染聊天框左侧列表
function renderChatList() {
    var ret = "";
    for (var userNameKey in receiveMsg) {
        if (containChatItems[userNameKey] === false) {
            ret = ret + " <div id=\"chatItem\" class='" + userNameKey + "' style=\"width: 145px;height: 30px;background: #01AAED;color: #00F7DE;font-size: 15px;padding:5px\">\n" +
                "                " + userNameKey + "\n" +
                "            </div>";
        }
        containChatItems[userNameKey] = true;
    }
    return ret;
}

function getRenderSendMsg(src, msg) {
    return "<div id=\"msg-item-r\" style=\"width: 450px;min-height: 40px; margin: 5px;float: right;\"> <div style=\"float: right;\"> <img src=\"" + src + "\" style=\"width: 40px;height: 40px;\"> </div> <div id=\"msg-item-content\" style=\"float:right;max-width: 350px; text-align:left; background: #2D93CA\"> " + msg + " </div> </div>"
}

function getRenderReceiveMsg(src, msg) {
    return "<div id=\"msg-item-l\" style=\"width: 450px;min-height: 40px; margin: 5px;float: left;\"> <div style=\"float: left;\"> <img src=\"" + src + "\" style=\"width: 40px;height: 40px;\"> </div> <div id=\"msg-item-content\" style=\"float:left;max-width: 350px; text-align:left; background: #2D93CA\"> " + msg + " </div> </div>"
}

function clearMap(map) {
    for (var key in map){
        delete map[key];
    }
}

Date.prototype.Format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return format;
};


